<?php
/**
 *  切片任务
 */
class clip_task_model{
	const TASK_C_STATE_ADD = 'add';
	const TASK_C_STATE_HANDLE = 'handle';
	const TASK_C_STATE_WAIT = 'wait';
	const TASK_C_STATE_OK = 'ok';
	const TASK_C_STATE_GET_MEDIA_URL_SUCC = 'get_media_url_succ';
	const TASK_C_STATE_GET_MEDIA_URL_FAIL = 'get_media_url_fail';
	const TASK_C_STATE_DOWNLOAD = 'download';
	const TASK_C_STATE_DOWNLOAD_SUCC = 'download_succ';
	const TASK_C_STATE_DOWNLOAD_FAIL = 'download_fail';
	const TASK_C_STATE_CLIPING = 'cliping';
	const TASK_C_STATE_CLIP_SUCC = 'clip_succ';
	const TASK_C_STATE_CLIP_FAIL = 'clip_fail';
	const TASK_C_STATE_CANCEL = 'cancel';
	const TASK_C_STATE_FAIL = 'fail';
	const TASK_C_STATE_C2_HANDLE = 'c2_handle';
	const TASK_C_STATE_C2_SUCC = 'c2_ok';
	const TASK_C_STATE_C2_FAIL = 'c2_fail';
	const TASK_C_STATE_C2_DELETE_HANDLE = 'c2_delete_handle';
	const TASK_C_STATE_C2_DELETE_SUCC = 'c2_delete_ok';
	const TASK_C_STATE_C2_DELETE_FAIL = 'c2_delete_fail';	
	
	static $task_state_arr = array(
	self::TASK_C_STATE_ADD    =>'添加任务',//执行成功
	self::TASK_C_STATE_HANDLE =>'任务已下发',//任务已下发（被切片工具取走）
	self::TASK_C_STATE_WAIT    =>'等待下发',//执行成功
	self::TASK_C_STATE_OK     =>'上报成功',//执行成功
	self::TASK_C_STATE_GET_MEDIA_URL_SUCC     =>'取片源下载地址成功',
	self::TASK_C_STATE_GET_MEDIA_URL_FAIL     =>'取片源下载地址失败',
	self::TASK_C_STATE_DOWNLOAD     =>'下载影片',//下载影片
	self::TASK_C_STATE_DOWNLOAD_SUCC     =>'下载成功',//下载影片
	self::TASK_C_STATE_DOWNLOAD_FAIL     =>'下载失败',//下载影片
	self::TASK_C_STATE_CLIPING      =>'正在切片',//正在切片
	self::TASK_C_STATE_CLIP_SUCC      =>'切片成功',
	self::TASK_C_STATE_CLIP_FAIL      =>'切片失败',
	self::TASK_C_STATE_CANCEL       =>'任务已取消',//任务取消
	self::TASK_C_STATE_FAIL         =>'切片失败',//切片失败
	self::TASK_C_STATE_C2_HANDLE         =>'执行注入',//
	self::TASK_C_STATE_C2_SUCC         =>'注入成功',
	self::TASK_C_STATE_C2_FAIL         =>'注入失败',
	self::TASK_C_STATE_C2_DELETE_HANDLE         =>'等待删除已注入片源',
	self::TASK_C_STATE_C2_DELETE_SUCC         =>'删除已注入片源成功',
	self::TASK_C_STATE_C2_DELETE_FAIL         =>'删除已注入片源失败',
	);
	static $task_type_default = 'std';
	/**
	 * 码流对应序号表
	 */
	static $mode_index = array(
	'std'=>'01',
	'hd'=>'02',
	'low'=>'03'
	);
	static public function get_kbps_index($mode){
		$mode= strtolower($mode);
		$mode_index = '01';
		if($mode && isset(self::$mode_index[$mode])){
			$mode_index = clip_task_model::$mode_index[$mode];
		}
		return $mode_index;
	}
	/**
	 * 添加任务
	 * 如果同一分集存在未处理的任务，则将其取消
	 * 如果是手动重发任务，则把优先级权重置为最高
	 * @param $task_info array(
	 * 'nns_task_type',
	 * 'nns_org_id',
	 * 'nns_video_id',
	 * 'nns_video_index_id',
	 * 'nns_index',//第几集
	 * 'nns_create_time',
	 * 'nns_force'  是否强制切片1：是 0：否
	 * )
	 */
	static public function add_task($task_info){
		$_params = array(
		'nns_vod_id'=>$task_info['nns_video_id'],
		'nns_vod_index_id'=>$task_info['nns_video_index_id']
		);
		$b_media_exists = self::_vod_media_exists($task_info);		
		if(!$b_media_exists){
			//该分集下还没有片源，不添加任务
			DEBUG && i_write_log('分集下还没有片源，不添加任务'.var_export($task_info,true));
			return false;
		}
		
		$db = nn_get_db(NL_DB_READ);
		$db_w = nn_get_db(NL_DB_WRITE);
		
		$task_info['nns_force']= $task_info['nns_force']?'1':'0';

		
		$cancel = self::$task_state_arr['cancel'];
		//删除之前的任务
		$sql = "select * from nns_mgtvbk_clip_task where nns_org_id='sihua' and   nns_video_type='".$task_info['nns_video_type']."' and nns_video_id='".$task_info['nns_video_id']."' and nns_video_index_id='".$task_info['nns_video_index_id']."'";
		$result = nl_db_get_all($sql,$db);
		if($result!=false && is_array($result)){
			foreach($result as $task_item){
				
				/*'nns_state' => self::TASK_C_STATE_ADD,
		'nns_desc'  => self::$task_state_arr[self::TASK_C_STATE_ADD],*/			
				$sql = "update nns_mgtvbk_clip_task  set nns_state='".self::TASK_C_STATE_ADD."',nns_desc='".self::$task_state_arr[self::TASK_C_STATE_ADD]."' where nns_id='".$task_item['nns_id']."'";
				
				nl_execute_by_db($sql,$db_w);
				$task_log = array(
				'nns_task_id' => $task_item['nns_id'],
				'nns_state'   => self::TASK_C_STATE_HANDLE,
				'nns_desc'    => self::$task_state_arr[clip_task_model::TASK_C_STATE_CANCEL],
				'nns_video_id'=>$task_info['nns_video_id'],
				'nns_video_index_id'=>$task_info['nns_video_index_id']
				);	
				self::add_task_log($task_log);
				//==========================================================================
				$task_log = array(
				'nns_task_id'=>$task_item['nns_id'],
				'nns_state' => self::TASK_C_STATE_ADD,
				'nns_desc'  => self::$task_state_arr[self::TASK_C_STATE_ADD],
				'nns_video_id'=>$task_info['nns_video_id'],
				'nns_video_index_id'=>$task_info['nns_video_index_id']
				);
				self::add_task_log($task_log);
				
				
				DEBUG && i_write_log('添加任务成功');
				if($task_info['nns_force']){//重切
					$sql = "update nns_mgtvbk_c2_task set nns_clip_task_id=null ,nns_action='add',nns_status=1 where nns_type='media' and nns_org_id='sihua' and nns_src_id='{$task_info['nns_video_index_id']}'";
				}else{
					$sql = "update nns_mgtvbk_c2_task set nns_clip_task_id='{$task_item['nns_id']}',nns_action='add',nns_status=1 where nns_type='media' and nns_org_id='sihua' and nns_src_id='{$task_info['nns_video_index_id']}'";
				}
				nl_execute_by_db($sql,$db_w);
				
			}
			
		}
		
		if(empty($task_info['nns_task_type'])){
			$task_info['nns_task_type'] = self::$task_type_default;
		}
		if(empty($task_info['nns_org_id'])){
			$task_info['nns_org_id'] = SP_ORG_ID;
		}		
		//if(empty($task_info['nns_id'])){
		//	$task_info['nns_id'] = np_guid_rand('cliptask'); 
		//}
		
        $task_info['nns_create_time'] = date('Y-m-d H:i:s');
        $task_info['nns_priority'] = 0;
        //生成任务内容
        /*
        $content = self:: _build_task_content($task_info);
        if($content==false){
        	i_write_log('没有生成任务内容，可能是不存在片源或者数据库执行失败');
        	return false;
        }
        $task_info['nns_content'] = $content;
        */
        unset($task_info['nns_index']);
		// $result = nl_db_insert($db_w,'nns_mgtvbk_clip_task',$task_info);
		// if($result == false){
        	// DEBUG && i_write_log('任务添加,数据库执行失败');
        	// return false;
		// }
		
		
		$sp_list = sp_model::get_sp_list();
		foreach ($sp_list as $key => $value) {
			// if(empty($task_info['nns_org_id'])){
				// $task_info['nns_org_id'] = isset($value['nns_id']) ? $value['nns_id'] :SP_ORG_ID;
			// }	
			// if(empty($task_info['nns_id'])){
				// $task_info['nns_id'] = np_guid_rand('cliptask'.$task_info['nns_org_id']);
				// $result = nl_db_insert($db_w,'nns_mgtvbk_clip_task',$task_info);
			// }else{
				// $task_info_update = $task_info;
				// $where = "nns_id='{$task_info['nns_id']}'";
				// unset($task_info_update['nns_id']);
				// $result = nl_db_update($db_w,'nns_mgtvbk_clip_task',$task_info_update,$where);
			// }
			$task_info['nns_org_id'] = isset($value['nns_id']) ? $value['nns_id'] :SP_ORG_ID;    
			$sql = "select * from nns_mgtvbk_clip_task where nns_org_id='{$task_info['nns_org_id']}' and nns_video_id='{$task_info['nns_video_id']}' and nns_video_index_id='{$task_info['nns_video_index_id']}'";
			$result = nl_db_get_one($sql, $db);
			if($result===false || $result===null){
				$task_info['nns_id'] = np_guid_rand('cliptask'.$task_info['nns_org_id']);
				$result = nl_db_insert($db_w,'nns_mgtvbk_clip_task',$task_info);
			}
			if($result == false){
	        	DEBUG && i_write_log('任务添加,数据库执行失败');
	        	continue;
			}
			
			$task_log = array(
				'nns_task_id'=>$task_info['nns_id'],
				'nns_state' => self::TASK_C_STATE_ADD,
				'nns_desc'  => self::$task_state_arr[self::TASK_C_STATE_ADD],
			);
			self::add_task_log($task_log);
			
			
			DEBUG && i_write_log('添加任务成功');
			if($task_info['nns_force']){//重切
				$sql = "update nns_mgtvbk_c2_task set nns_clip_task_id=null ,nns_action='add',nns_status=1 where nns_type='media' and nns_org_id='sihua' and nns_src_id='{$task_info['nns_video_index_id']}'";
			}else{
				$sql = "update nns_mgtvbk_c2_task set nns_clip_date='{$task_info['nns_date']}',nns_clip_task_id='{$task_info['nns_id']}',nns_action='add',nns_status=1 where nns_type='media' and nns_org_id='sihua' and nns_src_id='{$task_info['nns_video_index_id']}'";
			}
			nl_execute_by_db($sql,$db_w);
		}
		
		// $task_log = array(
		// 'nns_task_id'=>$task_info['nns_id'],
		// 'nns_state' => self::TASK_C_STATE_ADD,
		// 'nns_desc'  => self::$task_state_arr[self::TASK_C_STATE_ADD],
		// 'nns_video_id'=>$task_info['nns_video_id'],
		// 'nns_video_index_id'=>$task_info['nns_video_index_id']
		// );
		// self::add_task_log($task_log);

		//更新 新片源标识
		if($task_info['nns_video_type']=='0'){
			$sql = "update nns_vod_index set nns_new_media='0' where nns_id='".$task_info['nns_video_index_id']."'";
			nl_execute_by_db($sql,$db_w);
		}

								
		
		return true;
	}
	static public function _vod_media_exists($params){
		$sql = "select * from nns_vod_media where nns_deleted != 1 and  nns_vod_id='{$params['nns_video_id']}' and nns_vod_index_id='{$params['nns_video_index_id']}'";
		$db = nn_get_db(NL_DB_READ);
	
		$result = nl_query_by_db($sql,$db);	
		if($result===true) return false;
		return true;
	}
	/**
	 * 任务重发
	 */
	static public function restart_task($task_id,$force=false){
		$task_info = self::get_task_by_id($task_id);

		$task_info['nns_force']= $force?'1':'0';
		unset($task_info['nns_state']);
		unset($task_info['nns_content']);
		unset($task_info['nns_desc']);
		unset($task_info['nns_alive_time']);
		unset($task_info['nns_start_time']);
		unset($task_info['nns_end_time']);
		unset($task_info['nns_modify_time']);
		$add_task = self::add_task($task_info);
		if($add_task){
			$db = nn_get_db(NL_DB_READ);
			$sql = "select * from nns_vod_index where nns_id='".$task_info['nns_video_index_id']."'";
			$vod_index = nl_db_get_one($sql, $db);
			if($force){
				//强制重切
				$log_summary = "对【".$vod_index['nns_name']."】执行【强制重新切片】";
			}else{
				//重发任务
				$log_summary = "对【".$vod_index['nns_name']."】执行【重发任务任务】";
			}
			log_model::log_write($log_summary);
		}
		return $add_task;
	}
	static public function add_task_by_vod_id($vod_id){
		DEBUG && i_write_log('mgtv注入完成，开始添加任务...');
		$db = nn_get_db(NL_DB_READ);
		
		$sql = "select * from nns_vod_index where nns_deleted != 1 and  nns_vod_id='$vod_id'";
		$indexes = nl_db_get_all($sql,$db);
		if(is_array($indexes) && count($indexes)>0){
			foreach($indexes as $index_info){
				$task_info['nns_video_id'] = $index_info['nns_vod_id'];
				$task_info['nns_video_type'] = 0;
				$task_info['nns_video_index_id'] = $index_info['nns_id'];
				$task_info['nns_index'] = $index_info['nns_index'];
				self::add_task($task_info);
				
			}
		}else{
			DEBUG && i_write_log('影片下可能没有分集，或者数据库执行失败...');
		}
	}
	/**
	 * 有新片源的分集加入切片任务中
	 */
	static public function add_task_by_new_media($nns_vod_id){
		$db = nn_get_db(NL_DB_READ);
				
		//条件：有新片源，并且分分片信息已经注入,并且MEDIA_TIME_OUT 秒 没有片源更新;每次限制跑30条
		//$sql = "select i.* from nns_vod_index i join nns_mgtvbk_c2_task ct on ct.nns_ref_id=i.nns_id where (i.nns_new_media='1' && i.nns_new_media_time < NOW() - INTERVAL ".MEDIA_TIME_OUT." SECOND  or i.nns_new_media='' or ISNULL(i.nns_new_media) ) && ct.nns_type='index' && ct.nns_status=0 ";
		$sql = "select * from nns_vod_index where nns_deleted != 1 and  (nns_new_media='1' && nns_new_media_time < NOW() - INTERVAL ".MEDIA_TIME_OUT." SECOND  or nns_new_media='' or ISNULL(nns_new_media)) limit 30";
		if($nns_vod_id!=null){
			$sql = "select * from nns_vod_index where nns_deleted != 1 and nns_vod_id='$nns_vod_id'";
		}
		$indexes = nl_db_get_all($sql,$db);
		if(is_array($indexes) && count($indexes)>0){
			foreach($indexes as $index_info){
				$task_info['nns_video_type'] = 0;
				$task_info['nns_video_id'] = $index_info['nns_vod_id'];
				$task_info['nns_video_index_id'] = $index_info['nns_id'];
				$task_info['nns_index'] = $index_info['nns_index'];
				self::add_task($task_info);

			}
		}else{
			DEBUG && i_write_log('没有有新片源的分集');
		}		
	}
	static public function test_add_task_by_new_media(){
		DEBUG && i_write_log('--测试添加切片任务---');
		$db = nn_get_db(NL_DB_READ);
			
		//条件：有新片源，并且分分片信息已经注入,并且MEDIA_TIME_OUT 秒 没有片源更新;每次限制跑200条
		$sql = "select * from nns_vod_index  ";
		$indexes = nl_db_get_all($sql,$db);
		if(is_array($indexes) && count($indexes)>0){
			DEBUG && i_write_log('共添加分集:'.count($indexes));
			foreach($indexes as $index_info){
				$task_info['nns_video_type'] = 0;
				$task_info['nns_video_id'] = $index_info['nns_vod_id'];
				$task_info['nns_video_index_id'] = $index_info['nns_id'];
				$task_info['nns_index'] = $index_info['nns_index'];
				self::add_task($task_info);

			}
		}else{
			DEBUG && i_write_log('没有有新片源的分集');
		}		
	}
	/**
	 * 有新片源
	 */
	static public function update_new_media_state($vod){
		//i_write_log('影片('.$vod['vod_id'].')分集('.$vod['vod_index_id'].')-------有新片源---');
		$db = nn_get_db(NL_DB_WRITE);
	
		$str_sql = "update nns_vod_index set nns_new_media='{$vod['status']}',nns_new_media_time=now() where nns_id='{$vod['vod_index_id']}' and nns_vod_id='{$vod['vod_id']}' ";
		return nl_execute_by_db($str_sql,$db);
	}
	
	/**
	 * $param array('nns_video_id','nns_video_type','nns_video_index_id')
	 */
	static public function _build_task_content($param){
		$db = nn_get_db(NL_DB_READ);
		$db_w = nn_get_db(NL_DB_WRITE);
		
		$video_info = null;	
		$video_index_info = null;	
		$media_list = null;
		if($param['nns_video_type']==0){
			//vod
			$vod_id = $param['nns_video_id'];
			$sql = "select * from nns_vod where nns_id='".$vod_id."' and nns_deleted!=1";
			$video_info = nl_db_get_one($sql,$db);
			$sql = "select * from nns_vod_index where nns_id='".$param['nns_video_index_id']."' and nns_deleted!=1";
			$video_index_info = nl_db_get_one($sql,$db);
			$media_list = self::get_vod_media($param);
		}else{
			//live
			$live_id = $param['nns_video_id'];
			$sql = "select * from nns_live where nns_id='".$live_id."'";
			$video_info = nl_db_get_one($sql,$db);
			$sql = "select * from nns_live_index where nns_id='".$param['nns_video_index_id']."'";
			$video_index_info = nl_db_get_one($sql,$db);	
			$media_list = self::get_live_media($param);					
		}
		//			
		$force = !empty($param['nns_force'])?'1':'0';	
		$ret_xml = '';
		///$ret_xml .= '<nn_api>' ;
		$ret_xml .=	'<task id="'.$param['nns_id'].'" force="'.$force.'">';
		$ret_xml .= '<video id="'.$param['nns_video_id'].'" name="'.$video_info['nns_name'].'" video_type="'.$param['nns_video_type'].'" pinyin="'.$video_info['nns_pinyin'].'">';
		$ret_xml .=	'<index_list>';
		$ret_xml .= '<index id="'.$param['nns_video_index_id'].'" index="'.$video_index_info['nns_index'].'" name="'.$video_index_info['nns_name'].'">';
		$ret_xml .= '<media_list>';
		//$i = 1;
		foreach($media_list as $media_info){

			$kbps_index = self::get_kbps_index($media_info['nns_mode']);			
			include_once dirname(dirname(dirname(dirname(dirname(__FILE__))))).'/np/np_http_curl.class.php';
			$http_client = new np_http_curl_class();
			$url = MGTV_MEDIA_DOWNLOAD_URL.'?'.'file_id='.$media_info['nns_import_id'];
			$result = $http_client->get($url);
			$ret_arr = json_decode($result, true);
			if($ret_arr['err']=='0'){		
				$sql_c2_task = "select * from nns_mgtvbk_c2_task where nns_org_id='sihua' and nns_type='media' and nns_ref_id='{$media_info['nns_id']}'";				
				$c2_task_info = nl_db_get_one($sql_c2_task, $db);				
				if(is_array($c2_task_info)&&$c2_task_info!=false&&$c2_task_info!=null){
					$sql_update = "update nns_mgtvbk_c2_task set nns_modify_time=now(),nns_status=2,nns_action='modify',nns_clip_task_id=null,nns_clip_date=null where nns_id='{$c2_task_info['nns_id']}'";
					nl_execute_by_db($sql_update, $db_w);
				}else{
					$data = array(
						'nns_id'=>np_guid_rand(),
						'nns_type'=>'media',
						'nns_name'=>$video_index_info['nns_name'].'_'.$media_info['nns_mode'],
						'nns_ref_id'=>$media_info['nns_id'],
						'nns_action'=>'add',
						'nns_status'=>'1',
						'nns_create_time'=>date('Y-m-d H:i:s'),
						'nns_org_id'=>'sihua',
						'nns_src_id'=>$media_info['nns_vod_index_id'],
					);
					nl_db_insert($db_w, 'nns_mgtvbk_c2_task', $data);
				}
					
				//$kbps_index = $i;
				$ret_xml .= '<media id="'.$media_info['nns_id'].'" file_id="'.$media_info['nns_import_id'].'" content_id="'.$video_index_info['nns_import_id'].'" content_url="'.$media_info['nns_url'].'" kbps_index="0'.$kbps_index.'" kbps="'.$media_info['nns_kbps'].'"/>';
				
				
				//$i++;
			}else{
				continue;
			}
		}
		$ret_xml .= '</media_list>';
		$ret_xml .= '</index>';
		$ret_xml .=	'</index_list>';
		$ret_xml .= '</video>';
		$ret_xml .= '</task>';
		//$ret_xml .= '<result ret="0" reason="ok" />';
		//$ret_xml .= '</nn_api>';
		return $ret_xml;
	}
	/**
	 * 删除任务
	 */
	static public function delete_task($task_id){
		return true;	
		// $db = nn_get_db(NL_DB_WRITE);
// 
		// $sql = "delete from nns_mgtvbk_clip_task where nns_id='$task_id'";
		// return nl_execute_by_db($sql,$db);
	}
	/**
	 * 取切片任务
	 *  取优先级权重高的任务
	 */
	static public function get_task(){
		$db = nn_get_db(NL_DB_READ);
		
		$db_w = nn_get_db(NL_DB_WRITE);

		//and (ISNULL(nns_state) or nns_state='')
		$sql = "select * from nns_mgtvbk_clip_task " .
				"where  (ISNULL(nns_state) or nns_state='' or nns_state='add') " .
				" and nns_org_id='sihua'  order by nns_priority desc,nns_create_time desc limit 1";
		
		$task_info =  nl_db_get_one($sql,$db);
		if($task_info == false) return false;
		$b_media_exists = self::_vod_media_exists($task_info);
		if(!$b_media_exists){
			//该分集下还没有片源
			DEBUG && i_write_log('分集下还没有片源'.var_export($task_info,true));
			$sql = "update nns_mgtvbk_clip_task set nns_state='cancel' where nns_id='".$task_info['nns_id']."'";
			nl_execute_by_db($sql,$db_w);
			return false;
		}

		$task_info['nns_content'] = self:: _build_task_content($task_info);
		$nns_content = htmlspecialchars($task_info['nns_content']);
		$sql = "update nns_mgtvbk_clip_task set nns_content='".$nns_content."' where nns_id='".$task_info['nns_id']."'";
		$result = nl_execute_by_db($sql,$db_w);
		return $task_info;
	}
	/**
	 * 取任务下片源
	 */
	static public function get_vod_media($task_info){
		$db = nn_get_db(NL_DB_READ);

		$sql = "select * " .
				" from nns_vod_media" .
				" where " .
				"  nns_vod_id='".$task_info['nns_video_id']."' " .
				" and nns_vod_index_id='".$task_info['nns_video_index_id']."' and nns_deleted != 1 order by nns_kbps desc";
			
        return nl_db_get_all($sql,$db);
	}
	static public function get_live_media($task_info){
		$db = nn_get_db(NL_DB_READ);

		$sql = "select * " .
				" from nns_live_media" .
				" where " .
				"  nns_live_id='".$task_info['nns_video_id']."' " .
				" and nns_live_index_id='".$task_info['nns_video_index_id']."' ";
        return nl_db_get_all($sql,$db);
	}	
	/**
	 * @$params array('nns_video_id','nns_video_type','nns_video_index_id','nns_media_id')
	 */
	static public function get_media_info($params){
		$db = nn_get_db(NL_DB_READ);
	
		$media_info = null;
		if($params['nns_video_type']==0){
			//vod
			$sql = "select * from nns_vod_media where nns_id='".$params['nns_media_id']."'";
			$media_info= nl_db_get_one($sql,$db);
		}else{
			//live
			$sql = "select * from nns_live_media where nns_id='".$params['nns_media_id']."'";
			$media_info= nl_db_get_one($sql,$db);
		}
		return $media_info;
	}
	/**
	 * 如果删除分集，则取消该分集的任务
	 * @param nns_vod_index_id
	 * 
	 */
	static public function cancel_task_by_vod_index($nns_vod_index_id){
		DEBUG && i_write_log('删除分集，取消之前未处理任务'."\n vod_index_id:".$nns_vod_index_id);
		$db = nn_get_db(NL_DB_READ);
	
		//
		$sql = "select * from nns_mgtvbk_clip_task where  nns_video_type='0' and nns_video_index_id='".$nns_vod_index_id."'";
		$result = nl_db_get_all($sql,$db);
		if($result == false){
			return false;
		}
		foreach($result as $task_item){
				$result = self::update_task($task_item['nns_id'],array('nns_state'=>self::TASK_C_STATE_CANCEL,'nns_desc'=>self::$task_state_arr[self::TASK_C_STATE_CANCEL]));
				if($result!= false){
					//nns_task_id,nns_state,nns_desc
					$task_log = array(
					'nns_task_id'=>$task_item['nns_id'],
					'nns_state' => self::TASK_C_STATE_CANCEL,
					'nns_desc'  => self::$task_state_arr[self::TASK_C_STATE_CANCEL],
					'nns_video_index_id'=>$nns_vod_index_id,
					'nns_video_id'=>$task_item['nns_video_id'],
					
					);
					self::add_task_log($task_log);					
				}else{
					DEBUG && i_write_log('删除分集时，取消之前未处理任务执行失败');
				}			
		}
		DEBUG && i_write_log('取消之前未处理任务ok');
		return true;
	}
	static public function get_task_by_id($task_id){
		$db = nn_get_db(NL_DB_READ);
		
		$sql = "select * from nns_mgtvbk_clip_task where nns_id='$task_id' ";
		return nl_db_get_one($sql,$db);
	}
	static public function get_task_vod_info($task_id){
		$db = nn_get_db(NL_DB_READ);
			
		$sql="select SQL_CALC_FOUND_ROWS vod_index.nns_name as index_name,vod_index.nns_index as nns_index,vod.nns_name as vod_name,vod.nns_pinyin,task.* " .
				"from nns_mgtvbk_clip_task task inner join nns_vod vod on (
 task.nns_video_id=vod.nns_id
)  inner join nns_vod_index vod_index on (
 vod_index.nns_id=task.nns_video_index_id
) where  task.nns_id='$task_id'  " ;
        return nl_db_get_one($sql,$db);

	}
	/**
	 * 更新任务状态
	 * @param $state 0:任务完成 
	 */
	static public function update_task($task_id,$info){
		$db = nn_get_db(NL_DB_WRITE);		
		return nl_db_update($db,'nns_mgtvbk_clip_task',$info,"nns_id='".$task_id."'");
	}
	/**
	 * 添加到任务log
	 * $task_log array(nns_task_id,nns_state,nns_desc)
	 */
	static public function add_task_log($task_log){
		$db = nn_get_db(NL_DB_WRITE);
		$task_info = self::get_task_by_id($task_log['nns_task_id']);
		$task_log['nns_id'] = np_guid_rand();
		$task_log['nns_video_type'] = $task_info['nns_video_type'];
		$task_log['nns_video_id'] = $task_info['nns_video_id'];
		$task_log['nns_video_index_id'] = $task_info['nns_video_index_id'];
		$task_log['nns_create_time'] = date('Y-m-d H:i:s');
		return nl_db_insert($db,'nns_mgtvbk_clip_task_log',$task_log);
	}
	static public function get_task_detail_log($task_id){
        $db = nn_get_db(NL_DB_READ);
       
        $sql = "select * from nns_mgtvbk_clip_task_log where nns_task_id='$task_id' order by nns_create_time desc";
        return nl_db_get_all($sql,$db);
	}
	/*
	 * 取任务列表
	 * @param $filter array查询条件
	 * @return array('data'=>查询结果集,'rows'=>总记录数)
	 */
	static public function get_task_list($sp_id,$filter,$start=0,$size=100){
        $db = nn_get_db(NL_DB_READ);
     
        $wh = '';		
        if(!empty($filter['nns_name'])){
        	$wh .= " and (vod.nns_name like '%".$filter['nns_name']."%' or vod_index.nns_name like '%".$filter['nns_name']."%') ";
        }
        if(!empty($filter['nns_state'])){
        	if($filter['nns_state']=='wait'){
        		$wh .= " and (task.nns_state='' or task.nns_state is null) ";
        	}else{
        		$wh .= " and task.nns_state='".$filter['nns_state']."'";
        	}
           
        }
		
		if(!empty($filter['day_picker_start'])){
			$wh .= " and task.nns_create_time>='".$filter['day_picker_start']."'";
		}
		if(!empty($filter['day_picker_end'])){
			$wh .= " and task.nns_create_time<='".$filter['day_picker_end']."'";
		}
		
		if(!empty($filter['day_picker_put_start'])){
			$wh .= " and task.nns_alive_time>='".$filter['day_picker_put_start']."'";
		}
		if(!empty($filter['day_picker_put_end'])){
			$wh .= " and task.nns_alive_time<='".$filter['day_picker_put_end']."'";
		}
		
		
		if(!empty($filter['start_time'])){
			$wh .= " and task.nns_start_time>='".$filter['start_time']."'";
		}
		if(!empty($filter['end_time'])){
			$wh .= " and task.nns_end_time<='".$filter['end_time']."'";
		}
		
		if(!empty($filter['nns_id'])){
			$wh .= " and task.nns_id='".$filter['nns_id']."'";
		}
		
		
		
		$sql="select  vod_index.nns_name as index_name,vod_index.nns_index as nns_index,vod.nns_name as vod_name,vod.nns_pinyin,task.* " .
				"from nns_mgtvbk_clip_task task inner join nns_vod vod on (
 task.nns_video_id=vod.nns_id and task.nns_org_id='$sp_id'
)  inner join nns_vod_index vod_index on (
 vod_index.nns_id=task.nns_video_index_id
) where (task.nns_state!='cancel' or ISNULL(task.nns_state) or task.nns_state='') " .$wh;
		$sql .= " order by nns_priority desc,task.nns_create_time desc ";		
		$sql .= "limit $start,$size";
		$data =  nl_db_get_all($sql,$db);
		
    	$count_sql="select  count(*) as num " .
				"from nns_mgtvbk_clip_task task inner join nns_vod vod on (
 task.nns_video_id=vod.nns_id and task.nns_org_id='$sp_id'
)  inner join nns_vod_index vod_index on (
 vod_index.nns_id=task.nns_video_index_id
) where (task.nns_state!='cancel' or ISNULL(task.nns_state) or task.nns_state='') " .$wh;
    	$rows = nl_db_get_col($count_sql,$db);
    	
    	return array('data'=>$data,'rows'=>$rows);
	}
	/**
	 * $priority up:增加优先级 down：减少优先级权重 top:最高999 bottom:最低0
	 * 设置任务优先级 9999为最高 0为最低
	 */
	static public function set_task_priority($task_id,$priority='top'){
        $db_w = nn_get_db(NL_DB_WRITE);
     	/*
		if($priority == 'top'){
			$sql = "update nns_mgtvbk_clip_task SET nns_priority=9999 where nns_id='$task_id'";
			return nl_execute_by_db($sql,$db_w);
		}
		if($priority == 'bottom'){
			$sql = "update nns_mgtvbk_clip_task SET nns_priority=0 where nns_id='$task_id'";
			return nl_execute_by_db($sql,$db_w);
		}*/
				

		$sql = null;
		switch($priority){
			case 'top':
			$sql = "update nns_mgtvbk_clip_task SET nns_priority=9999 where nns_id='$task_id'";
			break;
			case 'up':
			$sql = "update nns_mgtvbk_clip_task SET nns_priority=LEAST(9999,nns_priority+1) where nns_id='$task_id'";
			break;
			case 'down':
			$sql = "update nns_mgtvbk_clip_task SET nns_priority=GREATEST(0,nns_priority-1) where nns_id='$task_id'";
			break;
			case 'bottom':
			$sql = "update nns_mgtvbk_clip_task SET nns_priority=0 where nns_id='$task_id'";
			break;						
		}
		if($sql != null){
			return nl_execute_by_db($sql,$db_w);
		}
		return false;
	}
	/**
	 * 是否可以删除切片
	*/
	static public function can_delete_clip_file($task_id){
		 $db = nn_get_db(NL_DB_READ);
		 
		 $sql =  "select * from nns_mgtvbk_clip_task where nns_id='".$task_id."' ";
		 $result = nl_query_by_db($sql,$db);
		 //任务已经不存在
		 if($result === true){
		 	return true;
		 }
		 
		 $sql =  "select * from nns_mgtvbk_clip_task where nns_id='".$task_id."' and nns_state='c2_ok'";
		 $result = nl_query_by_db($sql,$db);
		 //任务注入成功
		 if(is_array($result)){
		 	return true;
		 }
		 //其他情况不可以删除
		 return false; 
	}
	
	
	/**
	 * 是否可以删除切片
	 */
	static public function can_delete_clip_file_new($task_id){
		 $db = nn_get_db(NL_DB_READ);
		 
		 $sql =  "SELECT * FROM `nns_mgtvbk_c2_log` WHERE `nns_task_type` = 'Movie' AND `nns_action`='REGIST' AND `nns_task_id`='".$task_id."' limit 1";
		 
		 $result = nl_db_get_one($sql,$db);
		 if(empty($result)){
		 	//没有存在注入命令列表，不能删除
		 	return false;
		 }		
		 $ids = explode("_",$result['nns_url']);unset($result);		 
		 $vod_index_id = $ids[2]; 
		 
		 $sql = "SELECT * FROM `nns_mgtvbk_clip_task` where `nns_video_index_id`='".$vod_index_id."' and  ISNULL(nns_modify_time) ";
		 $result = nl_db_get_one($sql,$db);
		 if(is_array($result)&&$data!=null){
		 	return false;
		 }
		 $sql = "SELECT * FROM `nns_mgtvbk_clip_task` where `nns_video_index_id`='".$vod_index_id."' order by nns_modify_time desc limit 1";
		 //die($sql);
		 $result = nl_db_get_all($sql,$db); 
		 if(count($result)>0){
			 foreach ($result as  $value) {
				 if($value['nns_state']!='c2_ok'){
				 	//任务状态不是成功不可以删除	
				 	return false;
				 }
			 }
		 }else{
		 	//任务不存在可以删除
		 	return true;
		 }
		 //其他情况可以删除		 
		 return true;
	}
	
	static public function movie_c2_execute(){
		$db = nn_get_db(NL_DB_READ);
		$db_w = nn_get_db(NL_DB_WRITE);
		 
		$sql =  "select clip.nns_id as nns_id from nns_mgtvbk_clip_task as clip,nns_mgtvbk_c2_task c2 where clip.nns_video_index_id=c2.nns_ref_id and c2.nns_type='index' and c2.nns_status=0 and clip.nns_state='ok'  order by clip.nns_modify_time desc limit 30";
		$task_arr = nl_db_get_all($sql,$db);
		if(is_array($task_arr)){
			foreach($task_arr as $task_item){
				//
				$rs = c2_task_model::add_movies_by_clip_task($task_item['nns_id']);
				if($rs){	
					nl_execute_by_db("update nns_mgtvbk_clip_task set nns_state='c2_handle' where nns_id='".$task_item['nns_id']."'",$db_w);
				}					
			}
		}
	}
	static public function resend_movie_c2_execute(){
		$db = nn_get_db(NL_DB_READ);
		$db_w = nn_get_db(NL_DB_WRITE);
		 
		$sql =  "select clip.nns_id as nns_id from nns_mgtvbk_clip_task as clip,nns_mgtvbk_c2_task c2 where clip.nns_video_index_id=c2.nns_ref_id and c2.nns_type='index' and c2.nns_status=0 and clip.nns_state='c2_fail'  order by clip.nns_modify_time desc limit 100";
		$task_arr = nl_db_get_all($sql,$db);
		if(is_array($task_arr)){
			foreach($task_arr as $task_item){
				//
				$rs = c2_task_model::add_movies_by_clip_task($task_item['nns_id']);
				if($rs){	
					nl_execute_by_db("update nns_mgtvbk_clip_task set nns_state='c2_handle' where nns_id='".$task_item['nns_id']."'",$db_w);
				}					
			}
		}
	}	
	static public function delete_movie_by_task_id($task_ids){
		$db = nn_get_db(NL_DB_READ);
		$db_w = nn_get_db(NL_DB_WRITE);
		$ids = array();
		if(is_array($task_ids)){
			$ids = $task_ids;
		}else if(is_string($task_ids)){
			$ids[] = $task_ids;
		}
		if(empty($ids)) return ;				
		foreach($ids as $id){
			$task_info = self::get_task_by_id($id);
			//注入成功过的片源进行删除
			//$sql = "select * from nns_mgtvbk_clip_task_log where nns_video_index_id='".$task_info['nns_video_index_id']."' and nns_state='c2_ok' limit 1";
			
			//$result = nl_query_by_db($sql,$db);
			//if(!is_bool($result)){
				//删除媒体
				$sql = "select * from nns_vod_index where nns_id='".$task_info['nns_video_index_id']."'";
				$index_item = nl_db_get_one($sql,$db);
				if($index_item){
						
					$sql = "select nns_id from nns_vod_media where nns_vod_index_id='".$index_item['nns_id']."'";
					$vod_medias = nl_db_get_all($sql,$db);
					//删除媒体
					$media_ids = array();
					foreach($vod_medias as $item){
						$media_ids[] = $item['nns_id'];
					}
					//c2_task_model::delete_movies(array('nns_ids'=>$media_ids,'nns_task_id'=>$task_info['nns_id'],'nns_task_name'=>$index_item['nns_name']));
				    
					$log_summary = "删除【".$index_item['nns_name']."】的片源";
					log_model::log_write($log_summary);
				    //更改状态
					$dt = date('Y-m-d H:i:s');
					$set_state = array(
					'nns_state' => clip_task_model::TASK_C_STATE_C2_DELETE_HANDLE,
					'nns_desc' => clip_task_model::$task_state_arr[clip_task_model::TASK_C_STATE_C2_DELETE_HANDLE],
					'nns_modify_time'=>$dt,
					);
					clip_task_model::update_task($task_info['nns_id'], $set_state);
					
					$org_id = $task_info['nns_org_id'];
					$sql = "update nns_mgtvbk_c2_task set nns_action='destroy' ,nns_status=3 where nns_type='media' and nns_org_id='$org_id' and nns_src_id='{$index_item['nns_id']}' and nns_clip_task_id='{$task_info['nns_id']}'";
					
					nl_execute_by_db($sql,$db_w);
					
					
					//任务日志	
					$task_log = array(
					'nns_task_id' => $task_info['nns_id'],
					'nns_state'   => clip_task_model::TASK_C_STATE_C2_DELETE_HANDLE,
					'nns_desc'    => clip_task_model::$task_state_arr[clip_task_model::TASK_C_STATE_C2_DELETE_HANDLE],
					'nns_video_id'=>$vod_medias['nns_vod_id'],
					'nns_video_index_id'=>$vod_medias['nns_vod_index_id']
					);	
					$rs = clip_task_model::add_task_log($task_log);				    
				}
				
			//}
		}
        return true;
	}

	//通过任务列表添加新的切片任务
	static public function add_task_movie_clip($query){
		$db = nn_get_db(NL_DB_READ);				
		//条件：有新片源，并且分分片信息已经注入,并且MEDIA_TIME_OUT 秒 没有片源更新;每次限制跑30条		
		$vod_index_id = $_GET['nns_vod_index_id'];
		$where = "";
		if(!empty($vod_index_id)){
			$where = " and nns_id='".$vod_index_id."'";
		}
		$sql = "select * from nns_vod_index where nns_deleted != 1 and nns_vod_id='".$query['nns_vod_id']."' ".$where;
		$indexes = nl_db_get_all($sql,$db);
		if(is_array($indexes) && count($indexes)>0){
			foreach($indexes as $index_info){
				$task_info['nns_video_type'] = 0;
				$task_info['nns_video_id'] = $index_info['nns_vod_id'];
				$task_info['nns_video_index_id'] = $index_info['nns_id'];
				$task_info['nns_index'] = $index_info['nns_index'];
				self::add_task($task_info);
			}
		}else{
			DEBUG && i_write_log('没有有新片源的分集');
		}		
		return true;
	}
}
